package com.hotacorp.opencloud.userservice.service.impl;

import java.time.Duration;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotacorp.opencloud.common.mybatisplus.PageData;
import com.hotacorp.opencloud.common.mybatisplus.Query;
import com.hotacorp.opencloud.userservice.dao.SysTenantDao;
import com.hotacorp.opencloud.userservice.entity.SysTenantEntity;
import com.hotacorp.opencloud.userservice.service.SysTenantService;
import com.hotacorp.opencloud.userservice.util.UserConstants;

/**
 * 租户管理接口实现
 * @author lwg
 *
 */
@Service("sysTenantService")
public class SysTenantServiceImpl extends ServiceImpl<SysTenantDao, SysTenantEntity> implements SysTenantService {
	@Autowired
	private StringRedisTemplate redisTemplate;

    @Override
    public PageData queryPage(Map<String, Object> params) {
    	QueryWrapper<SysTenantEntity> query = new QueryWrapper<SysTenantEntity>();
    	if (StringUtils.isNotBlank((String)params.get("tenantname"))) query.like("tenantname", "%" + params.get("tenantname") + "%");
        IPage<SysTenantEntity> page = this.page(
                new Query<SysTenantEntity>().getPage(params),
                query
        );

        return new PageData(page);
    }

	@Override
	public Long getTenantId(String hostname) {
		String dddd = redisTemplate.boundValueOps(UserConstants.DOMAIN_KEY + ":" + hostname).get();
		if (dddd == null) {
			SysTenantEntity entity = baseMapper.selectOne(new QueryWrapper<SysTenantEntity>().eq("domain", hostname));
			if (entity != null) {
				String sss = String.valueOf(entity.getTenantid());
				redisTemplate.boundValueOps(UserConstants.DOMAIN_KEY + ":" + hostname).set(sss, Duration.ofMinutes(10));
				return entity.getTenantid();
			} else {
				redisTemplate.boundValueOps(UserConstants.DOMAIN_KEY + ":" + hostname).set("", Duration.ofMinutes(10 +(new Random()).nextInt(10)));
				return null;
			}
		} else if ("".equals(dddd)) {
			return null;
		} else {
			redisTemplate.boundValueOps(UserConstants.DOMAIN_KEY + ":" + hostname).expire(10, TimeUnit.MINUTES);
			return Long.valueOf(dddd);
		}
	}

}